package com.palfund.service;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

/**
 * 绑定的服务它的生命周期与和它绑定在一起的组件一样长.多个组件可以和同一个Service同时绑定,
 * 只有所有的绑定的组件都销毁的时候,该Service才会销毁.(bindService在主线程工作)
 * <p>
 * 只有一个Service的实例
 */

public class MainActivity extends AppCompatActivity {

    private Intent mStartOne;
    private ServiceConnection mConnection;
    private BindService mService;
    private CommunicationService.CommunicationBinder mBinder;
    private Intent mStartTwo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // bindService需要一定的时间,bindService()方法后直接调用操作service的方法会出现空指针异常
        bindServiceFun();
        //communicationFun();

    }

    private void bindServiceFun() {
        Intent bindService = new Intent(this, BindService.class);
        mConnection = new ServiceConnection() {
            //当与服务建立连接的调用
            //name:指的就是service;
            //service:与Activity等其他组件进行信息传递的一个通道.
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                BindService.CustomBinder customBinder = (BindService.CustomBinder) service;
                // 获取service对象
                mService = customBinder.getService();
                Log.i("MainActivity", "---onServiceConnected()--->" + "连接成功" + name);
            }

            //当与服务失去连接的时候调用.
            //通常只有这个服务被杀死或者因为其他意外原因而销毁的时候才会执行该方法.
            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.i("MainActivity", "---onServiceDisconnected()--->" + "断开连接");
            }
        };
        // 绑定服务
        // BIND_ABOVE_CLIENT:如果当绑定服务期间遇到OOM需要杀死进程,客户进程会先于服务进程被杀死.
        // BIND_ADJUST_WITH_ACTIVITY:允许客户进程提升被绑定服务进程的优先级
        // BIND_ALLOW_OOM_MANAGEMENT:如果绑定服务期间遇到OOM需要杀死进程,被绑定的服务进程会被OOM列入猎杀对象中.
        // BIND_AUTO_CREATE:若绑定服务时服务未启动,则会自动启动服务
        // BIND_DEBUG_UNBIND:使用此标志绑定服务之后的unBindService方法会无效.这种方法会引起内存泄露,只能在调试时使用.
        // BIND_IMPORTANT:被绑定的服务进程优先级会被提到FOREGROUND级别
        // BIND_NOT_FOREGROUND:被绑定的服务进程优先级不允许被提到FOREGROUND级别
        // BIND_WAIVE_PRIORITY:被绑定的服务进程不会被OOM列入猎杀对象中
        bindService(bindService, mConnection, BIND_AUTO_CREATE);
    }

    private void communicationFun() {
        Intent communication = new Intent(this, CommunicationService.class);
        ServiceConnection connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                mBinder = (CommunicationService.CommunicationBinder) service;
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };
        bindService(communication, connection, BIND_AUTO_CREATE);
    }

    public void click(View view) {
        switch (view.getId()) {
            case R.id.btn_startOne:
                mStartOne = new Intent(this, StartService.class);
                mStartOne.putExtra("index", 1);
                startService(mStartOne);
                break;
            case R.id.btn_startTwo:
                mStartTwo = new Intent(this, StartService.class);
                mStartTwo.putExtra("index", 2);
                startService(mStartTwo);
                break;
            case R.id.btn_startIntent:
                Intent intentService = new Intent(this, CustomIntentService.class);
                intentService.putExtra("info", "intentService");
                startService(intentService);
                break;
            case R.id.btn_bindService:
                //绑定和调用要有一定的时间间隔
                //bindServiceFun();
                int random = mService.getRandom();
                Toast.makeText(this, String.valueOf(random), Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_communication:
                // 可进行多次通信
                //包裹.Activity用来给Service传递信息的;
                Parcel data = Parcel.obtain();
                data.writeString("我是Activity,你好啊....");
                //Service给Activity回复信息所用的对象
                Parcel repley = Parcel.obtain();
                //传递信息的方法
                try {
                    mBinder.transact(IBinder.FIRST_CALL_TRANSACTION, data, repley, 0);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                //取出Service回复的信息
                String msg = repley.readString();
                Toast.makeText(MainActivity.this, "来自服务端的信息=" + msg, Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 停止service
        if (mStartOne != null) {
            stopService(mStartOne);
        }
        // 取消绑定,不取消绑定,会自动取消绑定但也会出现异常
        //unbindService(mConnection);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.NONE, 1, 1, "jump");
        menu.add(Menu.NONE, 2, 1, "stopService");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 1:
                startActivity(new Intent(this, TestActivity.class));
                break;
            case 2:
                stopService(mStartOne);
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
